<template>
    <div class="apply-container" v-loading="loading">
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span>{{ isEdit ? '编辑成果' : '申报成果' }}</span>
            </div>

            <el-form ref="achievementForm" :model="achievementForm" :rules="achievementRules" label-width="120px"
                class="achievement-form">
                <el-form-item label="成果标题" prop="title">
                    <el-input v-model="achievementForm.title" placeholder="请输入成果标题" maxlength="100" show-word-limit />
                </el-form-item>

                <el-form-item label="成果类型" prop="achievementType">
                    <el-select v-model="achievementForm.achievementType" placeholder="请选择成果类型" style="width: 100%">
                        <el-option label="论文" :value="1" />
                        <el-option label="专利" :value="2" />
                        <el-option label="竞赛证书" :value="3" />
                        <el-option label="项目计划" :value="4" />
                        <el-option label="其他" :value="5" />
                    </el-select>
                </el-form-item>

                <el-form-item label="成果描述" prop="description">
                    <el-input v-model="achievementForm.description" type="textarea" :rows="4"
                        placeholder="请详细描述您的成果内容、创新点、应用价值等" maxlength="1000" show-word-limit />
                </el-form-item>

                <el-form-item label="绑定课程">
                    <el-select v-model="achievementForm.course" placeholder="请选择相关课程（可选）" clearable style="width: 100%">
                        <el-option v-for="course in courseList" :key="course.id" :label="course.name"
                            :value="course.name" />
                    </el-select>
                </el-form-item>

                <el-form-item label="学期">
                    <el-select v-model="achievementForm.semester" placeholder="请选择学期（可选）" clearable style="width: 100%">
                        <el-option v-for="semester in semesterList" :key="semester.value" :label="semester.label"
                            :value="semester.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="级别">
                    <el-select v-model="achievementForm.level" placeholder="请选择级别（可选）" clearable style="width: 100%">
                        <el-option label="国家级" :value="1" />
                        <el-option label="省级" :value="2" />
                        <el-option label="市级" :value="3" />
                        <el-option label="校级" :value="4" />
                    </el-select>
                </el-form-item>

                <el-form-item label="指导教师" prop="teacherId">
                    <el-select v-model="achievementForm.teacherId" placeholder="请选择指导教师" clearable style="width: 100%">
                        <el-option v-for="teacher in teacherList" :key="teacher.id" :label="teacher.username"
                            :value="teacher.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="成果附件" prop="attachments">
                    <el-upload ref="upload" :action="uploadAction" :headers="uploadHeaders"
                        :file-list="attachmentFileList" :on-preview="handleAttachmentPreview"
                        :on-remove="handleAttachmentRemove" :before-upload="beforeAttachmentUpload"
                        :on-exceed="handleAttachmentExceed" :http-request="handleAttachmentUpload" multiple :limit="5"
                        accept=".pdf,.doc,.docx,.jpg,.jpeg,.png,.gif">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">
                            支持上传PDF、Word文档、图片等格式，单个文件不超过10MB，最多上传5个文件
                        </div>
                    </el-upload>

                    <!-- 文件预览列表 -->
                    <div v-if="attachmentFileList.length > 0" class="file-list-preview">
                        <div v-for="(file, index) in attachmentFileList" :key="index" class="file-item">
                            <i :class="getFileIcon(file.fileType)" class="file-icon" />
                            <span class="file-name">{{ file.name }}</span>
                            <span class="file-size">({{ formatFileSize(file.size) }})</span>
                            <span v-if="file.status" class="file-status" :class="file.status">
                                {{ file.status === 'success' ? '上传成功' : file.status === 'uploading' ? '上传中...' : '上传失败'
                                }}
                            </span>
                        </div>
                    </div>
                </el-form-item>


                <el-form-item>
                    <el-button type="primary" @click="submitForm" :loading="submitLoading">
                        {{ isEdit ? '更新成果' : '提交申报' }}
                    </el-button>
                    <el-button @click="handleCancel">取消</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import { submitAchievement, updateAchievement, getAchievementDetail, getCourseList, getSemesterList } from '@/api/achievement'
import { uploadFile } from '@/api/upload'
import { getToken } from '@/utils/auth'
import { getTeacherList } from '@/api/achievement'

export default {
    name: 'AchievementApply',
    data() {
        return {
            loading: false,
            submitLoading: false,
            isEdit: false,
            achievementId: null,
            achievementForm: {
                title: '',
                achievementType: '',
                description: '',
                course: '',
                semester: '',
                level: '',
                teacherId: ''
            },
            achievementRules: {
                title: [
                    { required: true, message: '请输入成果标题', trigger: 'blur' },
                    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
                ],
                achievementType: [
                    { required: true, message: '请选择成果类型', trigger: 'change' }
                ],
                description: [
                    { required: true, message: '请输入成果描述', trigger: 'blur' },
                    { min: 10, max: 1000, message: '描述长度在 10 到 1000 个字符', trigger: 'blur' }
                ],
                teacherId: [
                    { required: true, message: '请选择指导教师', trigger: 'change' }
                ]
            },
            attachmentFileList: [],
            courseList: [],
            teacherList: [],
            semesterList: [
                { label: '2024-2025学年第一学期', value: '2024-2025-1' },
                { label: '2024-2025学年第二学期', value: '2024-2025-2' },
                { label: '2023-2024学年第一学期', value: '2023-2024-1' },
                { label: '2023-2024学年第二学期', value: '2023-2024-2' }
            ],
            uploadAction: '',
            uploadHeaders: {
                'Authorization': 'Bearer ' + getToken()
            }
        }
    },
    created() {
        // 检查是否为编辑模式
        if (this.$route.query.id) {
            this.isEdit = true
            this.achievementId = this.$route.query.id
            this.loadAchievementData()
        }
        this.getCourseList()
        this.getTeacherList();
    },
    methods: {
        async loadAchievementData() {
            this.loading = true
            try {
                const res = await getAchievementDetail(this.achievementId)
                const data = res.data

                this.achievementForm = {
                    title: data.title,
                    achievementType: data.achievementType,
                    description: data.description,
                    course: data.course,
                    semester: data.semester,
                    level: data.level,
                    teacherId: data.teacherId
                }

                // 解析附件
                if (data.fileUrl) {
                    try {
                        this.attachmentFileList = JSON.parse(data.fileUrl)
                    } catch (e) {
                        console.error('解析附件数据失败:', e)
                        this.attachmentFileList = []
                    }
                } else {
                    this.attachmentFileList = []
                }
            } catch (error) {
                this.$message.error('加载成果数据失败')
            } finally {
                this.loading = false
            }
        },
        async getCourseList() {
            // 模拟课程数据
            this.courseList = [
                { id: 1, name: '人工智能导论' },
                { id: 2, name: '机器学习' },
                { id: 3, name: '深度学习' },
                { id: 4, name: '计算机视觉' },
                { id: 5, name: '自然语言处理' },
                { id: 6, name: '数据挖掘' },
                { id: 7, name: '算法设计与分析' },
                { id: 8, name: '软件工程' },
                { id: 9, name: '数据库系统' },
                { id: 10, name: '计算机网络' },
                { id: 11, name: '操作系统' },
                { id: 12, name: '编译原理' },
                { id: 13, name: '物联网技术' },
                { id: 14, name: '区块链技术' },
                { id: 15, name: '网络安全' }
            ]
        },
        async getTeacherList() {
            try {
                const res = await getTeacherList()
                if (res.code === 200 && res.data) {
                    this.teacherList = res.data
                } else {
                    this.teacherList = []
                    this.$message.error('获取教师列表失败')
                }
            } catch (error) {
                console.error('获取教师列表失败:', error)
                this.teacherList = []
                this.$message.error('获取教师列表失败')
            }
        },
        submitForm() {
            this.$refs.achievementForm.validate(async (valid) => {
                if (valid) {
                    this.submitLoading = true
                    try {
                        const formData = {
                            ...this.achievementForm,
                            fileUrl: JSON.stringify(this.attachmentFileList)
                        }

                        if (this.isEdit) {
                            formData.id = this.achievementId
                            await updateAchievement(formData)
                            this.$message.success('更新成功!')
                        } else {
                            await submitAchievement(formData)
                            this.$message.success('申报成功!');
                        }
                        this.$router.push('/achievement/my-achievements')
                    } catch (error) {
                        this.$message.error(this.isEdit ? '更新失败' : '申报失败')
                    } finally {
                        this.submitLoading = false
                    }
                }
            })
        },
        handleCancel() {
            this.$confirm('确定要取消吗？未保存的数据将丢失。', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '继续编辑',
                type: 'warning'
            }).then(() => {
                this.$router.push('/achievement/my-achievements')
            })
        },
        // 文件上传相关方法
        async handleAttachmentUpload(options) {
            const formData = new FormData()
            formData.append('file', options.file)

            try {
                const response = await uploadFile(formData)
                if (response.code === 200 && response.data) {
                    const fileData = {
                        name: response.data.name,
                        url: response.data.url,
                        fileType: response.data.fileType,
                        size: options.file.size,
                        originalName: options.file.name,
                        status: 'success',
                        uid: options.file.uid,
                        uploadTime: Date.now(),
                        responseCode: response.code,
                        responseMsg: response.msg,
                        responseMap: response.map
                    }

                    // 更新文件列表中对应的文件
                    const index = this.attachmentFileList.findIndex(file => file.uid === options.file.uid)
                    if (index !== -1) {
                        this.$set(this.attachmentFileList, index, fileData)
                    } else {
                        this.attachmentFileList.push(fileData)
                    }

                    this.$message.success('文件上传成功')
                } else {
                    throw new Error('上传失败')
                }
            } catch (error) {
                this.$message.error('文件上传失败: ' + error.message)
                // 移除上传失败的文件
                this.attachmentFileList = this.attachmentFileList.filter(file => file.uid !== options.file.uid)
            }
        },
        handleAttachmentPreview(file) {
            if (file.url) {
                window.open(file.url, '_blank')
            }
        },
        handleAttachmentRemove(file) {
            this.attachmentFileList = this.attachmentFileList.filter(item => item.uid !== file.uid)
        },
        beforeAttachmentUpload(file) {
            const isValidType = /\.(pdf|doc|docx|jpg|jpeg|png|gif)$/i.test(file.name)
            const isLt10M = file.size / 1024 / 1024 < 10

            if (!isValidType) {
                this.$message.error('只能上传 PDF、Word文档或图片格式的文件!')
                return false
            }
            if (!isLt10M) {
                this.$message.error('上传文件大小不能超过 10MB!')
                return false
            }

            // 添加到文件列表（显示上传中状态）
            this.attachmentFileList.push({
                name: file.name,
                size: file.size,
                status: 'uploading',
                uid: file.uid
            })

            return true
        },
        handleAttachmentExceed() {
            this.$message.warning('最多只能上传5个文件!')
        },
        getFileIcon(fileType) {
            const iconMap = {
                'pdf': 'el-icon-document',
                'doc': 'el-icon-document',
                'docx': 'el-icon-document',
                'jpg': 'el-icon-picture',
                'jpeg': 'el-icon-picture',
                'png': 'el-icon-picture',
                'gif': 'el-icon-picture'
            }
            return iconMap[fileType] || 'el-icon-document'
        },
        formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes'
            const k = 1024
            const sizes = ['Bytes', 'KB', 'MB', 'GB']
            const i = Math.floor(Math.log(bytes) / Math.log(k))
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
        }
    }
}
</script>

<style lang="scss" scoped>
.apply-container {
    padding: 20px;
    max-width: 800px;
    margin: 0 auto;
}

.achievement-form {
    max-width: 600px;
}

.file-list-preview {
    margin-top: 10px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 10px;
    background-color: #fafafa;
}

.file-item {
    display: flex;
    align-items: center;
    padding: 5px 0;
    border-bottom: 1px solid #eee;

    &:last-child {
        border-bottom: none;
    }
}

.file-icon {
    margin-right: 8px;
    color: #409EFF;
    font-size: 16px;
}

.file-name {
    flex: 1;
    font-size: 14px;
    color: #333;
}

.file-size {
    margin-left: 10px;
    font-size: 12px;
    color: #999;
}

.file-status {
    margin-left: 10px;
    font-size: 12px;

    &.success {
        color: #67c23a;
    }

    &.uploading {
        color: #409eff;
    }

    &.error {
        color: #f56c6c;
    }
}
</style>